<template>
  <view class="container">
    <!-- 顶部标题 -->
    <view class="header">
      <text class="title">购物车</text>
      <text class="edit" @tap="toggleEdit">{{ isEditing ? '完成' : '编辑' }}</text>
    </view>

    <!-- 购物车列表 -->
    <scroll-view scroll-y class="cart-list">
      <view class="cart-item" v-for="(item, index) in cartList" :key="index">
        <!-- 选择框 -->
        <checkbox 
          class="checkbox" 
          :checked="item.selected" 
          @tap="toggleSelect(index)"
          color="#ff5062"
        />
        
        <!-- 商品信息 -->
        <image :src="item.image" mode="aspectFill" class="product-image"></image>
        <view class="product-info">
          <text class="product-name text-ellipsis">{{ item.name }}</text>
          <text class="product-desc text-ellipsis">{{ item.description }}</text>
          <view class="price-box">
            <view class="price-info">
              <text class="current-price">¥{{ formatPrice(item.currentPrice) }}</text>
              <text class="unit">/{{ item.unit }}</text>
              <text class="original-price">¥{{ formatPrice(item.originalPrice) }}</text>
            </view>
            <view class="quantity-control">
              <view class="minus btn-click" @tap="updateCount(index, -1)">-</view>
              <input 
                disabled
                type="number" 
                class="quantity" 
                :value="item.count"
                @input="onCountInput($event, index)"
              />
              <view class="plus btn-click" @tap="updateCount(index, 1)">+</view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部结算栏 -->
    <view class="settlement-bar">
      <view class="select-all">
        <checkbox 
          :checked="isAllSelected" 
          @tap="toggleSelectAll"
          color="#ff5062"
        />
        <text>全选</text>
      </view>
      
      <!-- 非编辑模式：显示价格和结算按钮 -->
      <block v-if="!isEditing">
        <view class="price-info">
          <view class="total">合计：<text class="amount">¥{{ formatPrice(totalPrice) }}</text></view>
          <view class="discount">已优惠：<text class="amount">¥{{ formatPrice(discountPrice) }}</text></view>
        </view>
        <view 
          class="delete-btn btn-click" 
          :class="{ disabled: !hasSelected }" 
          @tap="checkout"
        >
          结算({{ selectedCount }})
        </view>
      </block>
      
      <!-- 编辑模式：显示删除按钮 -->
      <block v-else>
        <view class="btn-group">
          <view 
            class="delete-btn btn-click" 
            :class="{ disabled: !hasSelected }" 
            @tap="deleteSelected"
          >
            删除({{ selectedCount }})
          </view>
        </view>
      </block>
    </view>

    <!-- 商品状态弹出层 -->
	<u-popup
		:show="showStatusPopup"
		@close="closeStatusPopup"
		mode="bottom"
		:round="16"
		:safeAreaInsetBottom="true"
	>
		<view class="status-popup">
			<view class="popup-header">
				<text class="title">商品状态提醒</text>
				<text class="close" @tap="closeStatusPopup">×</text>
			</view>
			<scroll-view scroll-y class="popup-content">
				<view class="status-item" v-for="item in unavailableGoods" :key="item.id">
					<image class="goods-img" :src="item.image" mode="aspectFill"></image>
					<view class="goods-info">
						<view class="goods-name">{{item.name}}</view>
						<view class="goods-desc">{{item.description}}</view>
						<view class="price-info">
							<text class="current-price">￥{{item.currentPrice}}</text>
							<text class="original-price">￥{{item.originalPrice}}</text>
							<text class="status-tag" :class="item.status === 'soldOut' ? 'sold-out' : 'stock-out'">
								{{item.status === 'soldOut' ? '已下架' : `库存不足(剩余${item.stock})`}}
							</text>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="popup-footer">
				<button class="confirm-btn" @tap="closeStatusPopup">我知道了</button>
			</view>
		</view>
	</u-popup>
  </view>
</template>

<script setup>
import { onShow } from '@dcloudio/uni-app'
import { ref, computed } from 'vue'
import { formatPrice } from '../../utils/baseUtils'
import { CardUtil } from '../../utils/cartUtils'
import { ProductApi } from '../../utils/productUtils'

// 购物车数据
const cartList = ref([])
// 商品状态弹出层控制
const showStatusPopup = ref(false)
// 不可用商品列表
const unavailableGoods = ref([])
// 编辑模式状态
const isEditing = ref(false)
// 是否可以提交订单
const isCheck = ref(false)

// 每次显示页面时
onShow(() => {
  // 重置 CatBar
  CardUtil.initCatBar()
  // 获取购物车数据
  cartList.value = CardUtil.getCat()
})

// 去结算
const checkout = () => {
  if (!hasSelected.value) {
    uni.showToast({title: '请选择要结算的商品', icon: 'none'})
    return
  }  
  
  // 检查所选商品是否可以购买【未下架、商品数量不够等】
  let selectProducts = cartList.value.filter(item => item.selected)
  ProductApi.getUnProduct(selectProducts.map(item => item.id))
  .then(unProducts => {
	isCheck.value = false
	let soldOuts = unProducts.filter(item => item.status == 'soldOut')   // 下架的商品
	let stockOuts = unProducts.filter(item => item.status == 'stockOut')  // 库存不足的
	// 如果购买的商品包含下架商品【给与提示】
	if (soldOuts.length > 0) {
		unavailableGoods.value = soldOuts
		showStatusPopup.value = true
		return
	}
	// 如果购买的商品包含库存不足的【给与提示，并且将购买数量变为 1】
	if (stockOuts.length > 0) {
		unavailableGoods.value = stockOuts
		showStatusPopup.value = true
		let ids = stockOuts.map(item => item.id)
		selectProducts.forEach(item => {if (ids.includes(item.id)) item.count = 1})
		// 提交订单
		isCheck.value = true
		return
	}
	// 可以提交订单了
	isCheck.value = true
	gotoCheck()
  })
}

// 关闭状态弹出层触发
const closeStatusPopup = () => {
  // 关闭状态弹出层
  showStatusPopup.value = false
  gotoCheck()
}

const gotoCheck = () => {
	// 跳转结算页面
	if (isCheck.value) {
		// 跳转到结算页面
		const selectedItems = cartList.value.filter(item => item.selected)
		// 跳转到结算页面
		uni.navigateTo({
		  url: '/pages/order/settlement',
		  success: (res) => {
			// 通过 eventChannel 向被打开页面传送数据
			res.eventChannel.emit('acceptDataFromOpenerPage', {
			  selectedItems,
			  totalPrice: totalPrice.value,
			  discountPrice: discountPrice.value
			})
		  }
		})
	}
}

// 切换编辑模式
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}

// 切换商品选中状态
const toggleSelect = (index) => {
  cartList.value[index].selected = !cartList.value[index].selected
}

// 切换全选状态
const toggleSelectAll = () => {
  const newState = !isAllSelected.value
  cartList.value.forEach(item => {
    item.selected = newState
  })
}

// 更新商品数量
const updateCount = (index, delta) => {
	CardUtil.updateCount(cartList.value[index].id, delta, data => {
		cartList.value = data
	})
}

// 删除选中商品
const deleteSelected = () => {
  if (!hasSelected.value) {
    uni.showToast({title: '请选择要删除的商品', icon: 'none'})
    return
  }
  uni.showModal({title: '提示', content: '确定要删除选中的商品吗？',
    success: (res) => {
      if (res.confirm) {
        // 根据选中商品的ID删除购物车中的商品
        CardUtil.deleteByIds(cartList.value.filter(item => item.selected).map(item => item.id), data => {
			// 重置数据
			cartList.value = data
			// 退出编辑状态
			isEditing.value = false
		})
      }
    }
  })
}

// 是否全选
const isAllSelected = computed(() => {
  return cartList.value.length > 0 && cartList.value.every(item => item.selected)
})

// 选中商品总数
const selectedCount = computed(() => {
  return cartList.value.reduce((count, item) => {
    return count + (item.selected ? item.count : 0)
  }, 0)
})

// 总价
const totalPrice = computed(() => {
  return cartList.value.reduce((total, item) => {
    return total + (item.selected ? item.currentPrice * item.count : 0)
  }, 0)
})

// 总优惠金额
const discountPrice = computed(() => {
  return cartList.value.reduce((total, item) => {
    if (!item.selected || !item.originalPrice) return total
    return total + ((item.originalPrice - item.currentPrice) * item.count)
  }, 0)
})

// 是否有选中商品
const hasSelected = computed(() => {
  return cartList.value.some(item => item.selected)
})
</script>

<style lang="scss" scoped>
.container {
  background-color: #f7f7f7;
  padding-top: 88rpx;
  padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
}

.header {
  position: fixed;
  top: 80rpx;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
  
  .title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }
  
  .edit {
    font-size: 28rpx;
    color: #666;
  }
}

.cart-list {
  padding: 20rpx;
  padding-bottom: 120rpx;
  width: 95%;
  
  .cart-item {
    display: flex;
    align-items: flex-start;
    background: #fff;
    padding: 20rpx;
    margin-bottom: 20rpx;
    border-radius: 12rpx;
    transform: translateZ(0);
    will-change: transform, opacity;
    animation: fadeInRight 0.3s ease-out;
    animation-fill-mode: both;
    
    // 为每个商品添加延迟动画
    @for $i from 1 through 10 {
      &:nth-child(#{$i}) {
        animation-delay: #{$i * 0.05}s;
      }
    }
    
    // 删除动画
    &.deleting {
      animation: fadeOutLeft 0.3s ease-out forwards;
    }
    
    .checkbox {
      margin: 60rpx 20rpx 0 0;
      transform: scale(0.8);
      transition: transform 0.15s cubic-bezier(0.4, 0, 0.2, 1);
      will-change: transform;
      
      &:active {
        transform: scale(0.85);
      }
    }
    
    .product-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
      background: #f5f5f5;
      transition: transform 0.15s cubic-bezier(0.4, 0, 0.2, 1);
      will-change: transform;
      backface-visibility: hidden;
      
      &:active {
        transform: scale(0.95);
      }
    }
    
    .product-info {
      flex: 1;
      min-width: 0;
      display: flex;
      flex-direction: column;
      
      .product-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 8rpx;
        font-weight: 500;
        -webkit-line-clamp: 1;
        line-height: 1.4;
      }
      
      .product-desc {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 12rpx;
        -webkit-line-clamp: 1;
        line-height: 1.3;
      }
      
      .price-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .price-info {
          flex-shrink: 1;
          min-width: 0;
          margin-right: 20rpx;
          display: flex;
          align-items: baseline;
          flex-wrap: wrap;
          
          .current-price {
            font-size: 30rpx;
            color: #ff5062;
            font-weight: 500;
            margin-right: 4rpx;
          }
          
          .unit {
            font-size: 22rpx;
            color: #999;
            margin-right: 12rpx;
          }
          
          .original-price {
            font-size: 22rpx;
            color: #999;
            text-decoration: line-through;
          }
        }
        
        .quantity-control {
          flex-shrink: 0;
          display: flex;
          align-items: center;
          
          .minus, .plus {
            width: 56rpx;
            height: 56rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f5f5f5;
            font-size: 28rpx;
            color: #333;
            transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
            will-change: transform, opacity;
            backface-visibility: hidden;
            
            &:active {
              transform: scale(0.9);
              opacity: 0.8;
            }
          }
          
          .minus {
            border-radius: 4rpx 0 0 4rpx;
          }
          
          .plus {
            border-radius: 0 4rpx 4rpx 0;
          }
          
          .quantity {
            width: 70rpx;
            height: 56rpx;
            text-align: center;
            font-size: 26rpx;
            color: #333;
            background: #fff;
            border-top: 2rpx solid #f5f5f5;
            border-bottom: 2rpx solid #f5f5f5;
            transition: background-color 0.15s cubic-bezier(0.4, 0, 0.2, 1);
            will-change: background-color;
            
            &:focus {
              background: #f8f8f8;
            }
          }
        }
      }
    }
  }
}

.settlement-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 100rpx;
  z-index: 100;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
  animation: slideUp 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  transform: translateZ(0);
  will-change: transform, opacity;
  
  .select-all {
    display: flex;
    align-items: center;
    margin-right: 30rpx;
    
    checkbox {
      transform: scale(0.8);
      margin-right: 8rpx;
      transition: transform 0.15s cubic-bezier(0.4, 0, 0.2, 1);
      will-change: transform;
      
      &:active {
        transform: scale(0.9);
      }
    }
    
    text {
      font-size: 28rpx;
      color: #333;
    }
  }
  
  .price-info {
    flex: 1;
    
    .total {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 4rpx;
      
      .amount {
        color: #ff5062;
        font-weight: 500;
      }
    }
    
    .discount {
      font-size: 24rpx;
      color: #999;
      
      .amount {
        color: #ff5062;
      }
    }
  }
  
  .btn-group {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
  }
  
  .delete-btn, .checkout-btn {
    padding: 16rpx 32rpx;
    border-radius: 32rpx;
    font-size: 28rpx;
    text-align: center;
    transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
    will-change: transform, opacity;
    backface-visibility: hidden;
    
    &.disabled {
      opacity: 0.5;
      transition: none;
    }
    
    &:active:not(.disabled) {
      transform: scale(0.95);
    }
  }
  
  .delete-btn {
    background: #ff5062;
    color: #fff;
  }
  
  .checkout-btn {
    background: #fff;
    color: #333;
    border: 2rpx solid #ddd;
  }
}

.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}

/* 商品状态弹出层样式 */
.status-popup {
		background: #fff;
		max-height: 70vh;
		display: flex;
		flex-direction: column;
		
		.popup-header {
			position: relative;
			padding: 24rpx;
			text-align: center;
			border-bottom: 1rpx solid #f5f5f5;
			
			.title {
				font-size: 28rpx;
				font-weight: 500;
				color: #333;
			}
			
			.close {
				position: absolute;
				right: 24rpx;
				top: 50%;
				transform: translateY(-50%);
				font-size: 36rpx;
				color: #999;
				padding: 10rpx;
			}
		}
		
		.popup-content {
			flex: 1;
			padding: 24rpx;
			max-height: 60vh;
			
			.status-item {
				display: flex;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #f5f5f5;
				
				&:last-child {
					border-bottom: none;
				}
				
				.goods-img {
					width: 120rpx;
					height: 120rpx;
					border-radius: 8rpx;
					margin-right: 20rpx;
				}
				
				.goods-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					
					.goods-name {
						font-size: 26rpx;
						color: #333;
						line-height: 1.4;
					}
					
					.goods-desc {
						font-size: 24rpx;
						color: #999;
						margin: 8rpx 0;
					}
					
					.price-info {
						display: flex;
						align-items: center;
						
						.current-price {
							font-size: 28rpx;
							color: #ff6700;
							margin-right: 12rpx;
						}
						
						.original-price {
							font-size: 24rpx;
							color: #999;
							text-decoration: line-through;
							margin-right: 12rpx;
						}
						
						.status-tag {
							font-size: 22rpx;
							padding: 4rpx 16rpx;
							border-radius: 4rpx;
							
							&.sold-out {
								background: #f5f5f5;
								color: #999;
							}
							
							&.stock-out {
								background: #fff2f4;
								color: #ff6700;
								white-space: nowrap;
							}
						}
					}
				}
			}
		}
		
		.popup-footer {
			padding: 24rpx;
			border-top: 1rpx solid #f5f5f5;
			
			.confirm-btn {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				background: #ff6700;
				color: #fff;
				font-size: 28rpx;
				border-radius: 40rpx;
				border: none;
				
				&:active {
					opacity: 0.9;
				}
			}
		}
	}

// 优化动画关键帧
@keyframes fadeInRight {
  from {
    opacity: 0;
    transform: translate3d(30rpx, 0, 0);
  }
  to {
    opacity: 1;
    transform: translate3d(0, 0, 0);
  }
}

@keyframes fadeOutLeft {
  from {
    opacity: 1;
    transform: translate3d(0, 0, 0);
  }
  to {
    opacity: 0;
    transform: translate3d(-30rpx, 0, 0);
  }
}

@keyframes slideUp {
  from {
    transform: translate3d(0, 30rpx, 0);
    opacity: 0;
  }
  to {
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
}

// 数量变化��画
@keyframes bounce {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

// 选中状态动画
@keyframes checkBounce {
  0% {
    transform: scale(0.8);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(0.8);
  }
}

// 价格变化动画
@keyframes priceChange {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
    color: #ff3a4c;
  }
  100% {
    transform: scale(1);
  }
}

// 添加动画类
.price-animate {
  animation: priceChange 0.3s ease-out;
}

.quantity-animate {
  animation: bounce 0.3s ease-out;
}

.check-animate {
  animation: checkBounce 0.3s ease-out;
}
</style>
